// const app = getApp()
const util = require('../../utils/util.js')
const App = getApp()
const Dialog = require('tdesign-miniprogram/dialog/index')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    navStyle: [],
    goodsNum: '',
    slideProductList: [],
    exp_info: {},
    exp_info_cha: 0,
    allSelect: 'circle',
    num: 0,
    count: 0,
    // discountText: '未达满减金额',
    deliveryFee: 18, //配送费
    isDeliveryFee: 1,
    difference: 73, //差额
    isDifference: 0,
    goPay: 0, //0加入购物车；1支付确认；2支付成功
    empty_image: util.Background_base64('static/image/goods/wujieguo.png'), // 空状态图标
    RecommendList: [], // 推荐商品列表
    clickItem: {},
    disable: false
    // actList: [],
    // fullReduce: null
  },
  //返回上一页
  navigateBack: function () {
    if (this.data.goPay == 1) {
      this.setData({
        goPay: 0
      })
    } else {
      util.navigateBack()
    }
  },
  change: function (e) {
    let that = this
    let selected = 0,
      stype = 'circle'
    let { index, select, id } = e.currentTarget.dataset
    //请求接口更改数据
    if (select == 'circle') {
      stype = 'success'
      selected = 1
    }
    //type 1为更改数量 2为更改选中状态
    util
      .request(
        '/api/cart/changcart',
        {
          id,
          selected,
          type: 2
        },
        'POST'
      )
      .then((res) => {
        const result = res.data
        if (result.code !== 0) {
          return wx.showToast({
            title: result.msg,
            icon: 'none'
          })
        }

        let newList = that.data.slideProductList
        newList[index].select = stype
        const cart = wx.getStorageSync('cart')
        cart.some((value) => {
          if (value.id == id) {
            if (value.select) value.select = 0
            else value.select = 1
            return true
          }
          return false
        })
        wx.setStorageSync('cart', cart)
        that.setData({
          slideProductList: newList
        })
        that.countNum()
        that.count()
      })
  },
  addtion: async function (e) {
    if (this.data.disable) return
    // 防止频繁点击
    this.data.disable = true
    var that = this
    var index = e.currentTarget.dataset.index
    var cate_id = e.currentTarget.dataset.id
    var num = e.currentTarget.dataset.num
    let clickItem = e.currentTarget.dataset.item
    //判断缓存是否存在token
    const token = wx.getStorageSync('token')
    //默认99件
    if (num < 99) {
      num++
    }
    var newList = that.data.slideProductList
    newList[index].goods_number = num
    //请求接口更改数据
    await util
      .request(
        '/api/cart/changcart',
        {
          id: cate_id,
          goods_number: num,
          token: token
        },
        'POST'
      )
      .then((res) => {
        console.log('加商品成功')
        that.getCartList()
        this.data.disable = false
      })
    that.setData({
      goodsNum: num,
      slideProductList: newList
    })
    that.countNum()
    that.count()
  },
  inputNum: function (e) {
    var num = e.detail.value
    this.setData({
      goodsNum: num
    })
  },
  numIputBlur: function (e) {
    var that = this
    var num = that.data.goodsNum
    var index = e.currentTarget.dataset.index
    var newList = that.data.slideProductList
    if (num == '') {
      //盘空
      newList[index].num = 1
      that.setData({
        slideProductList: newList
      })
    } else if (num < 1) {
      that.setData({
        goodsNum: newList[index].num,
        slideProductList: newList
      })
      wx.showToast({
        title: '该商品不能减少了哦~',
        icon: 'none'
      })
    } else if (num > 300) {
      that.setData({
        goodsNum: newList[index].num,
        slideProductList: newList
      })
      wx.showToast({
        title: '该商品最多购买300件哦~',
        icon: 'none'
      })
    } else {
      newList[index].num = num
      that.setData({
        slideProductList: newList
      })
    }
    that.countNum()
    that.count()
  },
  //减法
  subtraction: function (e) {
    var that = this
    var index = e.currentTarget.dataset.index
    var num = e.currentTarget.dataset.num
    var cate_id = e.currentTarget.dataset.id
    var newList = that.data.slideProductList
    //判断缓存是否存在token
    const token = wx.getStorageSync('token')
    if (num == 1) {
      //当数量为1件时，再次点击移除该商品
      // newList.splice(index, 1)
      wx.showToast({
        title: '该商品不能减少了~',
        icon: 'none'
      })
    } else {
      num--
      newList[index].goods_number = num
      //请求接口更改数据
      util
        .request(
          '/api/cart/changcart',
          {
            id: cate_id,
            goods_number: num,
            token: token
          },
          'POST'
        )
        .then((res) => {
          console.log('减商品成功')
          that.getCartList()
        })
    }
    that.setData({
      goodsNum: num,
      slideProductList: newList
    })
    that.countNum()
    that.count()
  },
  //全选
  allSelect: function (e) {
    var that = this
    var newList = that.data.slideProductList
    let cart = wx.getStorageSync('cart')
    if (e) {
      var allSelect = e.currentTarget.dataset.select //先判断是否选中
      if (allSelect == 'circle') {
        for (var i = 0; i < newList.length; i++) {
          newList[i].select = 'success'
          cart[i].select = 1
        }
        var select = 'success'
      } else {
        for (var i = 0; i < newList.length; i++) {
          newList[i].select = 'circle'
          cart[i].select = 0
        }
        var select = 'circle'
      }
    }

    that.setData({
      slideProductList: newList,
      allSelect: select
    })
    wx.setStorageSync('cart', cart)
    that.countNum()
    that.count()
  },

  countNum: function (datas) {
    //计算数量
    var that = this
    if (datas != undefined) {
      var newList = datas
    } else {
      var newList = that.data.slideProductList
    }
    var allNum = 0
    for (var i = 0; i < newList.length; i++) {
      if (newList[i].select == 'success') {
        allNum += parseInt(newList[i].goods_number)
      }
    }
    that.setData({
      num: allNum
    })
    console.log('jisuan')
    if (allNum) {
      wx.setTabBarBadge({
        index: 2,
        text: String(allNum)
      })
    } else {
      wx.removeTabBarBadge({
        index: 2
      })
    }
  },

  count: function (datas) {
    //计算金额方法
    var that = this
    if (datas != undefined) {
      var newList = datas
    } else {
      var newList = that.data.slideProductList
    }
    var newCount = 0,
      newCha = 0
    for (var i = 0; i < newList.length; i++) {
      if (newList[i].select == 'success') {
        newCount += newList[i].goods_number * parseFloat(newList[i].price)
      }
    }
    // let discountText = '未达满减金额！'
    // let price = newCount

    // const fullReduceRuler = this.data.fullReduce[0]
    // const { actcount, actdiscount } = fullReduceRuler
    // if (newCount >= actcount) {
    //   price = price - parseInt(actdiscount)
    //   discountText = `已减${actdiscount}元`
    // }
    that.setData({
      // discountText,
      //优惠卷金额
      // count: price.toFixed(2),
      count: newCount.toFixed(2),
      exp_info: {
        ...this.data.exp_info,
        cha: newCha
      }
    })
  },
  //支付--跳转确认订单
  async handleOrderPay(e) {
    if (util.isLogin() !== true) {
      return false
    }
    var that = this
    var newList = that.data.slideProductList //商品信息

    var count = that.data.count //合计金额
    try {
      //组合体参数
      const cart = newList
      let cart_ids = []
      cart.forEach((v) => {
        if (v.select == 'success') {
          cart_ids.push(v.id)
        }
      })
      //判断是否存在商品信息
      if (cart_ids.length <= 0 || cart_ids == []) {
        wx.showToast({
          title: '请选择下单商品',
          icon: 'error',
          duration: 1000 //持续的时间
        })
        return false
      }
      var urlPay = '/pages/confirmcart/confirmcart?cartIds=' + cart_ids.join(',')
      wx.navigateTo({
        url: urlPay
      })
    } catch (error) {
      wx.showToast({
        title: error
      })
    }
  },
  //获取活动规则列表
  // getDiscountRulerList: function () {
  //   util.request('/api/ad/getad', {}, 'GET').then((res) => {
  //     if (res.data.code !== 0) return
  //     let actList = res.data.data
  //     if (!actList.length) return
  //     const fullReduce = actList.filter((item) => item.acttype === 1)
  //     this.setData({ actList, fullReduce })
  //     console.log(this.data)
  //   })
  // },
  //获取购物车列表
  getCartList: function () {
    var that = this
    util.request('/api/cart/index', {}, 'GET').then((res) => {
      if (res.data.code !== 0) {
        return
      }
      var datas = res.data.data.cart_list
      var exp_info = res.data.data.exp_info
      var exp_info_cha = res.data.data.exp_info.cha.toFixed(2)
      wx.setStorageSync('cart', datas)
      // if (cartList.length == 0) {
      //   // 获取推荐商品
      //   that.getRecommend()
      // }
      for (var i = 0; i < datas.length; i++) {
        if (datas[i].select) datas[i].select = 'success'
        if (!datas[i].select) datas[i].select = 'circle'
      }
      that.count(datas)
      that.countNum(datas)
      that.setData({
        slideProductList: datas,
        exp_info: exp_info,
        exp_info_cha: exp_info_cha
      })
    })
  },
  // 获取推荐商品
  // async getRecommend() {
  //   util.request('/api/goods/tjgoods', {}, 'GET').then(response => {
  //     this.setData({
  //       RecommendList: response.data
  //     })
  //   })
  // },

  //删除全部
  async isDel(e) {
    if (util.isLogin() !== true) {
      return false
    }
    var that = this
    var newList = that.data.slideProductList
    var ids = []
    newList.forEach((v) => {
      if (v.select == 'success') {
        ids.push(v.id)
      }
    })

    const delParams = {
      ids
    }
    util.request('/api/cart/removecart', delParams, 'POST').then((res) => {
      console.log(res)
      var res = res.data.code
      if (res == 0) {
        wx.showToast({
          title: '删除成功',
          icon: 'loading...', //图标，支持"success"、"loading"
          //image: '/images/tan.png',//自定义图标的本地路径，image 的优先级高于 icon
          duration: 2000, //提示的延迟时间，单位毫秒，默认：1500
          mask: true, //是否显示透明蒙层，防止触摸穿透，默认：false
          success: function () {
            that.getCartList()
            setTimeout(function () {
              wx.redirectTo({
                url: '/pages/shopcart/shopcart'
              })
            }, 1000)
          },
          fail: function () {},
          complete: function () {}
        })
      } else {
        wx.showToast({
          title: '删除失败'
        })
      }
    })
  },
  //删除单条
  async isDelOne(e) {
    const dialogConfig = {
      context: this,
      title: '',
      closeOnOverlayClick: true,
      content: '确认要删除当前商品吗？',
      confirmBtn: '确定',
      cancelBtn: '取消'
    }
    Dialog.default
      .confirm(dialogConfig)
      .then(() => {
        // 确认删除
        var ids = []
        ids.push(e.currentTarget.dataset.id)
        const delParams = {
          ids
        }
        util.request('/api/cart/removecart', delParams, 'POST').then((res) => {
          var res = res.data.code
          let _this = this
          if (res == 0) {
            wx.showToast({
              title: '删除成功',
              icon: 'loading...', //图标，支持"success"、"loading"
              //image: '/images/tan.png',//自定义图标的本地路径，image 的优先级高于 icon
              duration: 2000, //提示的延迟时间，单位毫秒，默认：1500
              mask: true, //是否显示透明蒙层，防止触摸穿透，默认：false
              success: function () {
                _this.getCartList()
                setTimeout(function () {
                  wx.redirectTo({
                    url: '/pages/shopcart/shopcart'
                  })
                }, 1000)
              },
              fail: function () {},
              complete: function () {}
            })
          } else {
            wx.showToast({
              title: '删除失败'
            })
          }
        })
      })
      .catch(() => {
        // 取消删除
      })
    if (util.isLogin() !== true) {
      return false
    }
  },
  //   跳转详情
  goDetail(e) {
    wx.navigateTo({
      url: '/modules/goodsModule/pages/goodsinfo/goodsinfo?id=' + e.currentTarget.dataset.id
    })
  },
  // 跳转商品分类页面
  goshopping() {
    wx.switchTab({
      url: '/pages/shoplist/shoplist'
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // this.allSelect()

    this.setData({
      navStyle: App.globalData,
      isIphoneX: App.globalData.isIphoneX
    })
    if (util.isLogin() === true) {
      // this.getDiscountRulerList()
      this.getCartList()
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (util.isLogin() === true) {
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {}
})
